package com.be.beadmin.service.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring bean工具类
 */
@Component
public class BeanUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		BeanUtil.applicationContext = applicationContext;
	}

	/** 
	 * @return spring容器上下文
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	/** 
	 * 根据bean类型获取实例
	 * @param requiredType 实例类型
	 * @return bean实例
	 */
	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}


	/**
	 * 根据Bean的Name获取实例
	 *
	 * @param name Bean的名称
	 * @return bean实例
	 * @throws BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		return (T) applicationContext.getBean(name );
	}

}
